// 读取货号状态

import { CollectState, ProcessState, PushState, StateType } from '@/config';
import { ProductInfo } from './dianxiaomi';
import { GigaProductDetialInfo } from './giga';
import { toast } from 'sonner';
import { getAllFileHandleByDirectoryHandle } from './utils';

// 根据货号目录读取产品的采集状态
export interface State {
  [StateType.collect]: CollectState;
  [StateType.process]: ProcessState;
  [StateType.push]: PushState;
  collectErrorMessage?: string;
  processErrorMessage?: string;
  pushErrorMessage?: string;
}
export async function getProductState(
  stateFilename: string,
  directorHandle: FileSystemDirectoryHandle,
): Promise<State> {
  try {
    const infoFileHandle = await directorHandle.getFileHandle(stateFilename, {
      create: false,
    });
    const infoFile = await infoFileHandle.getFile();
    // 读取文件中的 state 属性
    const text = await infoFile.text();
    try {
      const state = JSON.parse(text);
      return {
        [StateType.collect]: CollectState.init,
        [StateType.process]: ProcessState.init,
        [StateType.push]: PushState.init,
        ...state,
      };
    } catch (error) {
      return {
        [StateType.collect]: CollectState.init,
        [StateType.process]: ProcessState.init,
        [StateType.push]: PushState.init,
      };
    }
  } catch (error) {
    return {
      [StateType.collect]: CollectState.init,
      [StateType.process]: ProcessState.init,
      [StateType.push]: PushState.init,
    };
  }
}

// 根据货号目录设置产品的状态
export async function setProductState(
  state: Partial<State>,
  stateFilename: string,
  directorHandle: FileSystemDirectoryHandle,
) {
  const infoFileHandle = await directorHandle.getFileHandle(stateFilename, {
    create: true,
  });
  const infoFile = await infoFileHandle.getFile();
  const text = await infoFile.text();
  let info = {} as State;
  try {
    info = JSON.parse(text);
    info = {
      ...info,
      ...state,
    };
  } catch (error) {
    info = {
      [StateType.collect]: CollectState.init,
      [StateType.process]: ProcessState.init,
      [StateType.push]: PushState.init,
      ...state,
    };
  }
  const writable = await infoFileHandle.createWritable();
  await writable.write(JSON.stringify(info));
  await writable.close();
}

// 读取货号目录下 giga 采集的信息
export async function getCollectedGigaProductDetailInfo(
  skuInfoDirectoryHandle: FileSystemDirectoryHandle,
  filename: string,
): Promise<GigaProductDetialInfo | null> {
  try {
    const fileHandle = await skuInfoDirectoryHandle.getFileHandle(filename, {
      create: false,
    });
    const file = await fileHandle.getFile();
    const text = await file.text();
    return JSON.parse(text);
  } catch (error) {
    console.log(error);
    return null;
  }
}

// 读取货号目录下的产品信息
export async function getProducInfo(
  skuInfoDirectoryHandle: FileSystemDirectoryHandle,
  filename: string,
): Promise<ProductInfo | null> {
  try {
    const fileHandle = await skuInfoDirectoryHandle.getFileHandle(filename, {
      create: false,
    });
    const file = await fileHandle.getFile();
    const text = await file.text();
    return JSON.parse(text);
  } catch (error) {
    console.log(error);
    return null;
  }
}

// 保存产品的信息到本地磁盘
export async function saveProductInfo({
  productInfo,
  productInfoFilename,
  skuIdInfoDirectoryHandle,
}: {
  productInfo: ProductInfo;
  productInfoFilename: string;
  skuIdInfoDirectoryHandle: FileSystemDirectoryHandle;
}) {
  const fileHandle = await skuIdInfoDirectoryHandle.getFileHandle(productInfoFilename, {
    create: true,
  });
  const file = await fileHandle.getFile();
  const text = await file.text();
  let newProductInfo: ProductInfo = {} as ProductInfo;
  try {
    const oldProductInfo: ProductInfo = JSON.parse(text);
    newProductInfo = {
      ...oldProductInfo,
      ...productInfo,
    };
  } catch (error) {
    newProductInfo = productInfo;
  }
  const fileWriter = await fileHandle.createWritable();
  await fileWriter.write(JSON.stringify(newProductInfo));
  await fileWriter.close();
}

// 保存文件
export async function saveFile(text: string, fileName: string) {
  const fileHandle = await window.showSaveFilePicker({
    suggestedName: fileName,
  });
  const fileWriter = await fileHandle.createWritable();
  await fileWriter.write(text);
  await fileWriter.close();
}

// 导入文件
export async function importFile() {
  const fileHandle = await window.showOpenFilePicker({
    id: 'file',
  });
  const loadingId = toast.loading('正在导入文件');
  try {
    const settingsFile = await fileHandle[0].getFile();
    const content = await settingsFile.text();
    toast.success(`成功导入`);
    toast.dismiss(loadingId);
    return content;
  } catch (error) {
    toast.error(`导入失败 ${(error as Error).message}`);
    toast.dismiss(loadingId);
  }
}

// 移除一个目录下的所有文件
export async function removeAllFilesInDirectory(directoryHandle: FileSystemDirectoryHandle) {
  const files = await getAllFileHandleByDirectoryHandle(directoryHandle);
  await Promise.all(
    files.map((file) => {
      return file.remove();
    }),
  );
}
